package com.crrc.dataparse.monitor.rsp.service.parse.treat.templatepara.datatrans;

import com.crrc.dataparse.templatepara.IDataTrans;
import com.crrc.dataparse.templatepara.datatrans.utils.DataTranslator;
import java.math.BigDecimal;

/*
     2进制转10进制低端在前
 */
public class BinaryToDecimalist extends IDataTrans {
    public BinaryToDecimalist() {
    }
    @Override
    public String trans(String value, double resolusion, double offset) {
        if (!DataTranslator.isValid(value)) {
            return null;
        } else {
            if (value.length() % 8 == 0) {
                StringBuffer sb = new StringBuffer();

                for(int i = value.length() - 1; i >= 0; i -= 8) {
                    for(int j = 7; j >= 0; --j) {
                        sb.append(value.charAt(i - j));
                    }
                }

                value = sb.toString();
            }

            long result = Long.valueOf(value, 2);
            float resolusion_f = (float)resolusion;
            float offset_f = (float)offset;
            double resultValue = (new BigDecimal(result)).multiply(new BigDecimal(String.valueOf(resolusion_f))).add(new BigDecimal(String.valueOf(offset_f))).doubleValue();
            return String.valueOf(resultValue);
        }
    }
}

